package cn.quevo.core.file;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.imageio.ImageIO;

import cn.quevo.core.exception.CheckParamsException;
import cn.quevo.core.lang.StringUtils;

/**
 * 图片压缩
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018-03-09 15:04:43
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @return
 */
public class FileCompression {
    private static String[] _imgs = new String[]{".jpg", ".jpeg", ".png", ".gif"};

    /**
     * 图片压缩
     *
     * @param input    图片流
     * @param fileName 图片名称
     * @param savePath 保存路径
     * @param _width   压缩后的图片宽度
     * @return
     * @throws Exception
     * @author July july_sky@foxmail.com
     * @date 2017年8月30日 下午2:36:12
     */
    public static Images copyLocation(InputStream input, String fileName, String savePath, int _width) throws Exception {
        String suffix = FileUtils.getFileSuffix(fileName);
        if (!StringUtils.contains(suffix.toLowerCase(), _imgs)) {
            throw new CheckParamsException(6100, "图片格式错误");
        }
        Path path = Paths.get(savePath);
        if (Files.notExists(path)) {
            Files.createDirectories(path);
        }
        //fileName = fileName.split("\\.")[0] + "_" + _width + suffix;
        fileName = StringUtils.getImgThum(fileName,"_"+_width);
        path = path.resolve(fileName).normalize();
        try {
            BufferedImage bufferedImage = ImageIO.read(input);      // 构造Image对象
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            BigDecimal bg = new BigDecimal((_width * 1d) / (width > height ? height : width)).setScale(2, RoundingMode.UP);
            double scale = bg.doubleValue();
            width = Double.valueOf(width * scale).intValue();
            height = Double.valueOf(height * scale).intValue();
            Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();
            ImageIO.write(outputImage, suffix.substring(1), path.toFile());
            Images images = new Images();
            images.setWidth(width);
            images.setHeight(height);
            return images;
        } catch (Exception e) {
            throw e;
        }
    }
}
